package com.javandad.app.server.servlet;

import java.util.LinkedList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpSession;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.javandad.app.client.fodos.FodosService;
import com.javandad.app.server.db.DatabaseManager;
import com.javandad.app.server.db.PMFSingleton;
import com.javandad.app.server.entity.Fodo;
import com.javandad.app.shared.entity.User;

@SuppressWarnings("serial")
public class FodosImpl extends RemoteServiceServlet implements FodosService {

	DatabaseManager dbm = DatabaseManager.getDefaultDatabaseManager();

	@Override
	public List<String> getSessionInfo() {
		List<String> list = new LinkedList<String>();
		HttpSession session = this.getThreadLocalRequest().getSession();
		list.add((String) session.getAttribute("mode"));
		list.add((String) session.getAttribute("username"));

		return list;

	}

	@Override
	public List<Long> getFodos(String username, String directory) {
		//HttpSession session = this.getThreadLocalRequest().getSession();
		List<Fodo> fodos = DatabaseManager.getDefaultDatabaseManager()
				.getFodos(username, directory, PMFSingleton.getPM());
		List<Long> ids = new LinkedList<Long>();
		for (Fodo f : fodos) {
			ids.add(f.getId());
		}
		return ids;

	}

	@Override
	public boolean setAsProfileFodo(String id) {
		PersistenceManager pm = PMFSingleton.getPM();
		HttpSession session = this.getThreadLocalRequest().getSession();
        User user = (User) session.getAttribute("user");
		try {
			Fodo nfodo = DatabaseManager.getDefaultDatabaseManager().getFodo(user.getUsername(),
					Long.valueOf(id.trim()), pm);
			
			if (nfodo != null){
				if (nfodo.getType() == null && !nfodo.equals(Fodo.PROFILE_FODO)){
					nfodo.setType(Fodo.PROFILE_FODO);


				}else{
					return false;
				}
			}else{

				return false;
			}

			List<Fodo> fodos = DatabaseManager.getDefaultDatabaseManager().getFodos(user.getUsername(),null,
					Fodo.PROFILE_FODO, pm);
			if (fodos != null)
				for (Fodo f : fodos){
					f.setType(null);
					pm.makePersistent(f);
				}
				


			pm.makePersistent(nfodo);

			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}finally{
			pm.close();

		}
	}

	@Override
	public boolean deleteFodos(List<Long> ids) {
		HttpSession session = this.getThreadLocalRequest().getSession();
        User user = (User) session.getAttribute("user");
		PersistenceManager pm = PMFSingleton.getPM();
         
        
		for (long id : ids){
			Fodo fodo = DatabaseManager.getDefaultDatabaseManager().getFodo(user.getUsername(),id, pm);
		    pm.deletePersistent(fodo);	
		}
		
		pm.close();
		return true;
	}

	
}
